# -*- encoding:utf-8 -*-
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response  # 如果是django用 from django.http.response import HttpResponse
from rest_framework import status

import logging
# 与配置文件的 LOGGING['loggers']下的'django'名一一对应
logger = logging.getLogger('django')

from redis import RedisError
def custom_exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常类
    :param context: 抛出异常的上下文
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法
    response = exception_handler(exc, context)

    if response is None:
        """到这里只有2中情况，要么程序没出错，要么出错了 django或者 restframework 没识别到"""
        view = context['view']
        if isinstance(exc, DatabaseError) or isinstance(exc,RedisError):
            # 数据库异常 或者 redis 异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误,请联系工作人员'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response





































